package com.apache.flow.taskHandler;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.jbpm.api.TaskService;
import org.jbpm.api.cmd.Command;
import org.jbpm.api.cmd.Environment;
import org.jbpm.api.task.Task;
import org.jbpm.pvm.internal.task.TaskImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.flow.core.entity.FlowAutomaticProcessing;
import com.apache.flow.core.manager.FlowAutomaticProcessingManager;
import com.apache.flow.core.manager.FlowDeployManager;

public class ZbxTask implements Command<Boolean> {
	private Logger logger = LoggerFactory.getLogger(ZbxTask.class);
	private static final long serialVersionUID = 1L;
	private String parentTaskId;//父任务Id  
	private Task CurTask;//当前节点  
	private Map<String, String> variables;//存放传递参数的Map集合

	public ZbxTask(Task joinTask, Map<String, String> variables) {
		this.CurTask = joinTask;
		this.variables = variables;
	}

	/**
	 * 流程执行方法
	 */
	public Boolean execute(Environment environment) throws Exception {
		TaskService taskService = environment.get(TaskService.class);

		String taskId = CurTask.getId();
		logger.info("流程执行方法开始执行,当前节点【" + CurTask.getName() + "     taskId=" + taskId + "】");
		Map<String, Object> mapVar = taskService.getVariables(taskId, taskService.getVariableNames(taskId));
		Iterator<String> mpIt = mapVar.keySet().iterator();
		logger.info("审核前,流程变量中已经存在的参数");
		while (mpIt.hasNext()) {
			String mpKey = mpIt.next();
			String mapValue = mapVar.get(mpKey) == null ? "" : mapVar.get(mpKey).toString();
			logger.info(mpKey + "    " + mapValue);
		}
		logger.info("审核前,流程变量中已经存在的参数遍历结束");

		Map<String, String> var = new HashMap<String, String>();
		if (variables != null && variables.size() > 0) {//此处采用业务系统新传过来的参数，覆盖可能已经存在的流程变量参数
			Iterator<String> it = variables.keySet().iterator();
			logger.info("任务审核开始前,当前节点" + CurTask.getName() + ",传递过来的参数");
			while (it.hasNext()) {
				String key = it.next();
				if (null != key && !"".equals(key) && !"taskId".equals(key) && !"result".equals(key)
						&& !"httpRand".equals(key)) {
					String value = variables.get(key);
					var.put(key, value);
					logger.info(key + "    " + value);
				}
			}
			logger.info("任务审核开始前,当前节点" + CurTask.getName() + ",传递过来的参数遍历结束");
		}

		String taskType = (String) taskService.getVariable(taskId, "taskType");
		logger.info("获取任务类型参数taskType=" + taskType);
		String result = variables.get("result");//获取审核意见
		logger.info("获取到审核参数result=" + result);

		if (taskType.equals(TaskType.AUTO)) {//自处理任务
			FlowAutomaticProcessingManager automaticProcessingManager = environment
					.get(FlowAutomaticProcessingManager.class);
			//任务表删除任务
			FlowAutomaticProcessing flowAutomaticProcessing = automaticProcessingManager
					.getAutomaticProcessingByNodeId(taskId);
			if (flowAutomaticProcessing != null) {
				automaticProcessingManager.deleteAutomaticProcessing(flowAutomaticProcessing);
			} else {
				return false;
			}
			logger.info("删除自处理任务成功,taskId为：" + taskId);

			var.put("approve", "0");
			var.put("result", result);
			var.put("notapprove", "0");
			taskService.completeTask(taskId, var);

			return true;
		}
		TaskImpl taskImpl = (TaskImpl) CurTask;
		//parentTaskId =(String)taskService.getVariable(taskId, "parentTaskId"); 
		parentTaskId = taskImpl.getSuperTask().getId();
		logger.info("获取到审核参数parentTaskId=" + parentTaskId);
		String taskExeType = (String) taskService.getVariable(taskId, "taskExeType");
		logger.info("获取到审核参数taskExeType=" + taskExeType);
		String strApprove = (String) taskService.getVariable(taskId, "approve");
		String strNotapprove = (String) taskService.getVariable(taskId, "notapprove");
		if (strApprove == null) {
			strApprove = "0";
		}
		if (strNotapprove == null) {
			strNotapprove = "0";
		}

		int approve = Integer.parseInt(strApprove);//同意票数
		logger.info("获取到审核参数,同意票数为" + approve);
		int notapprove = Integer.parseInt(strNotapprove);//不同意票数
		logger.info("获取到审核参数,不同意票数为" + notapprove);
		if (result != null && "T".equals(result)) {
			approve++;
			logger.info("taskId为：" + taskId + "的任务,审核意见为同意,当前同意票数为：" + approve + ",当前不同意票数为：" + notapprove);
		} else {
			notapprove++;
			logger.info("taskId为：" + taskId + "的任务,审核意见为不同意,当前同意票数为：" + approve + ",当前不同意票数为：" + notapprove);
		}
		String assignee = CurTask.getAssignee();
		Map<String, String> map = new HashMap<String, String>();
		map.put("lastUser", assignee);//保存上一审核人
		logger.info("保存任务转发人参数  lastUser=" + assignee);
		//修改历史表中的执行人记录
		FlowDeployManager flowDeployManager = environment.get(FlowDeployManager.class);
		if (!"T".equals(result)) {
			assignee = assignee + "^";
		}
		flowDeployManager.update(taskId, assignee);

		//处理当前任务
		taskService.setVariables(taskId, map);
		taskService.completeTask(taskId);
		int subTask = taskService.getSubTasks(parentTaskId).size();

		String calcuateResult = getResult(subTask, approve, notapprove, taskExeType);
		if ("G".equals(calcuateResult)) {//继续在该节点执行
			var.put("approve", "" + approve);
			var.put("notapprove", "" + notapprove);
			logger.info("当前节点审核继续：节点名称>" + CurTask.getName() + " 审核人为>" + assignee + "  审核结果为>" + calcuateResult
					+ "   其中审核通过票数为>" + approve + "   审核不通过票数为>" + notapprove);
			taskService.setVariables(parentTaskId, var);

			return false;
		} else if ("T".equals(calcuateResult) || "F".equals(calcuateResult)) {//该节点已经结束   包括通过与不通过
			var.put("approve", "0");
			var.put("result", calcuateResult);
			var.put("notapprove", "0");
			taskService.setVariables(parentTaskId, var);
			logger.info("当前节点审核结束：节点名称>" + CurTask.getName() + " 审核人为>" + assignee + "  审核结果为>" + calcuateResult
					+ "   同时初始化下一审核节点的审核同意与不同意票数为0");
			taskService.completeTask(parentTaskId);

			return true;
		} else {
			logger.error("判断当前节点是否审核完成时，返回结果有误");
			throw new Exception("判断当前节点是否审核完成时，返回结果有误");
		}

	}

	/**
	 * 
	 * @param subTask  子任务
	 * @param approve   同意数
	 * @param notapprove  不同意数
	 * @param taskExeType  任务类型
	 * @return
	 * <p>@description 判断流程是否执行结束
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-22 下午04:38:16
	 */
	public String getResult(int subTask, int approve, int notapprove, String taskExeType) {
		logger.info("流程审核：任务类型为>" + taskExeType + "  尚未审核人数>" + subTask + "  审核通过票数>" + approve + "  审核不通过票数>"
				+ notapprove);
		if (taskExeType.equals(TaskExeType.GRAB)) {//抢占
			if (approve > 0) {
				return "T";
			}
			if (notapprove > 0) {
				return "F";
			}
		} else if (taskExeType.equals(TaskExeType.ALLAGREE)) {//集体全部同意
			if (subTask == 0 && notapprove == 0) {
				return "T";
			}
			if (notapprove > 0) {//只要有一个不同意的，则结果为不通过
				return "F";
			}
		} else if (taskExeType.equals(TaskExeType.HALFAGREE)) {//集体半数同意
			int total = subTask + approve + notapprove;
			if (isHalf(approve, total)) {
				return "T";
			}
			if (isHalf(notapprove, total)) {
				return "F";
			}
		} else if (taskExeType.equals(TaskExeType.HALFAGREEALLVOTE)) {//全部表决，半数同意
			int total = subTask + approve + notapprove;
			if (subTask == 0) {//子任务为0，表示已经全部表决
				if (isHalf(approve, total)) {//同意票数超过半数
					return "T";
				}
				if (isHalf(notapprove, total)) {//不同意票数超过半数
					return "F";
				}
			}
		}
		return "G";//表示未结束，继续在该节点执行
	}

	/**
	 * 
	 * @param approve
	 * @param total
	 * @return
	 * <p>@description 是否超过半数
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午05:25:55
	 */
	public boolean isHalf(int approve, int total) {
		int left = total - approve;
		if (approve >= left) {
			return true;
		}

		return false;
	}

}
